#pragma once
#include <queue>
#include "customer.h"
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>

using namespace std;

class queue_sim
{
private:
	vector<int> waited;
	queue<customer> waitline;
	int tellers;

	double calculate_average_wait(vector<int> &v)
	{
		int sum_wait = 0;
		for (auto &w : v)
			sum_wait += w;
		return (double)sum_wait / (double)v.size();
	}

public:

	queue_sim() : tellers(0)
	{
		srand(time(NULL));
	}

	~queue_sim()
	{
	}



	double run_sim(int tellers, int duration, int num_runs = 10)
	{
		vector<int> runs;
		for (int run = 0; run < num_runs; run++)
		{
			waited.clear();
			while (waitline.size() != 0)
				waitline.pop();
			vector<customer> servicing;
			for (int i = 0; i < duration; i++)
			{
				//Service all customers and remove thoose whoose errands are complete
				for (auto it = servicing.begin(); it != servicing.end();)
				{
					it->incr_serviced();
					if (it->errand_complete())
						it = servicing.erase(it);
					else
						it++;
				}
				if ((rand() % 100) < 90)
					waitline.push(customer(i, rand() % 7 + 2));
				while (servicing.size() < tellers && !waitline.empty())
				{
					waited.push_back(waitline.front().get_wait_time(i));
					servicing.push_back(waitline.front());
					waitline.pop();
				}
			}
			
			runs.push_back(calculate_average_wait(waited));
		}
		return calculate_average_wait(runs);
	}
};

